﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using NHibernate.Cfg;
using NHibernate;
using NHibernate.Context;
using System.Web.Handlers;
namespace Guoc.DAL.Common
{
    /// <summary>
    /// HHibernate 帮助类
    /// </summary>
    public sealed class NhibernateHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";
        private static readonly ISessionFactory sessionFactory;
        //静态构造函数只会调用一次
        static NhibernateHelper()
        {
            sessionFactory = new Configuration().Configure().BuildSessionFactory();
        }

        public static ISession GetCurrentSession()
        {
            HttpContext context = HttpContext.Current;           
            
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;
            
            if (currentSession == null)
            {
                currentSession = sessionFactory.OpenSession();
                context.Items[CurrentSessionKey] = currentSession;
               
            }
            return currentSession;
        }

        public static void CloseSession()
        {
            HttpContext context = HttpContext.Current;            
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;
            if (currentSession == null)
            {
                // No current session
                return;
            }
            currentSession.Close(); 
            context.Items.Remove(CurrentSessionKey);
           
        }

        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }
    }
}

